package com.lulu.baselib.api.Interceptor;

import com.lulu.baselib.util.StringUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Author: XuChang
 * Date: 2019/10/22 22:21
 * Email: 123286473@qq.com
 * Description:保持seesionId
 * History:
 */
public class SessionKeepInterceptor implements Interceptor {

    static List<String> cookies = new ArrayList<>();

    /**
     * 退出登陆时需要清空，重新获取seesionId
     */
    public static void clearCookies() {
        cookies.clear();
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        if (cookies.size() != 0) {
            Request.Builder builder = chain.request().newBuilder();
            for (String cookie : cookies) {
                if (StringUtil.isNotEmpty(cookie))
                    builder.addHeader("Cookie", cookie);
            }
            request = builder.build();
        }
        Response originalResponse = chain.proceed(request);
        if (cookies.size() == 0 && !originalResponse.headers("Set-Cookie").isEmpty()) {
            for (String header : originalResponse.headers("Set-Cookie")) {
                cookies.add(header);
            }
        }

        return originalResponse;
    }
}
